# 待办清单路由
from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from models import db
from models.todo import Todo
from datetime import datetime, date

todo_bp = Blueprint('todo', __name__, url_prefix='/todo')

@todo_bp.route('/')
def list_todos():
    """显示待办清单页面"""
    return render_template('todo.html')

@todo_bp.route('/api/todos', methods=['GET'])
def get_todos():
    """获取待办列表（支持过滤和搜索）"""
    # 获取查询参数
    priority = request.args.get('priority')
    category = request.args.get('category')
    status = request.args.get('status')
    search = request.args.get('search')
    
    # 构建查询
    query = Todo.query
    
    if priority:
        query = query.filter_by(priority=priority)
    
    if category:
        query = query.filter_by(category=category)
    
    if status == 'completed':
        query = query.filter_by(completed=True)
    elif status == 'pending':
        query = query.filter_by(completed=False)
    
    if search:
        query = query.filter(Todo.title.contains(search))
    
    # 排序：未完成在前，按截止日期和优先级排序
    todos = query.order_by(Todo.completed, Todo.deadline, Todo.priority.desc()).all()
    
    return jsonify({
        'todos': [todo.to_dict() for todo in todos]
    })

@todo_bp.route('/api/todos', methods=['POST'])
def create_todo():
    """创建新待办事项"""
    data = request.json
    
    # 解析截止日期
    deadline = None
    if data.get('deadline'):
        try:
            deadline = datetime.fromisoformat(data['deadline'].replace('Z', '+00:00'))
        except:
            pass
    
    # 创建待办事项
    todo = Todo(
        title=data['title'],
        description=data.get('description', ''),
        priority=data.get('priority', 'medium'),
        category=data.get('category', '其他'),
        deadline=deadline
    )
    
    db.session.add(todo)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'todo': todo.to_dict()
    }), 201

@todo_bp.route('/api/todos/<int:todo_id>', methods=['PUT'])
def update_todo(todo_id):
    """更新待办事项"""
    todo = Todo.query.get_or_404(todo_id)
    data = request.json
    
    # 更新字段
    if 'title' in data:
        todo.title = data['title']
    if 'description' in data:
        todo.description = data['description']
    if 'priority' in data:
        todo.priority = data['priority']
    if 'category' in data:
        todo.category = data['category']
    if 'completed' in data:
        todo.completed = data['completed']
    if 'deadline' in data:
        try:
            todo.deadline = datetime.fromisoformat(data['deadline'].replace('Z', '+00:00'))
        except:
            pass
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'todo': todo.to_dict()
    })

@todo_bp.route('/api/todos/<int:todo_id>', methods=['DELETE'])
def delete_todo(todo_id):
    """删除待办事项"""
    todo = Todo.query.get_or_404(todo_id)
    db.session.delete(todo)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'message': '删除成功'
    })

@todo_bp.route('/api/todos/<int:todo_id>/toggle', methods=['POST'])
def toggle_todo(todo_id):
    """切换完成状态"""
    todo = Todo.query.get_or_404(todo_id)
    todo.completed = not todo.completed
    db.session.commit()
    
    return jsonify({
        'success': True,
        'completed': todo.completed
    })

@todo_bp.route('/api/stats', methods=['GET'])
def get_stats():
    """获取统计信息"""
    total = Todo.query.count()
    completed = Todo.query.filter_by(completed=True).count()
    pending = total - completed
    
    # 今日到期（修复：使用UTC时间）
    now_utc = datetime.utcnow()
    today_utc = now_utc.date()
    today_deadline = Todo.query.filter(
        Todo.completed == False,
        db.func.date(Todo.deadline) == today_utc
    ).count()
    
    # 逾期（修复：使用UTC时间比较）
    overdue = Todo.query.filter(
        Todo.completed == False,
        Todo.deadline < now_utc
    ).count()
    
    return jsonify({
        'total': total,
        'completed': completed,
        'pending_count': pending,
        'today_deadline': today_deadline,
        'overdue': overdue
    })

@todo_bp.route('/api/today', methods=['GET'])
def get_today_todos():
    """获取今日待办"""
    # 修复：使用UTC时间
    today_utc = datetime.utcnow().date()
    todos = Todo.query.filter(
        Todo.completed == False,
        db.func.date(Todo.deadline) == today_utc
    ).all()
    
    return jsonify({
        'todos': [todo.to_dict() for todo in todos]
    })

@todo_bp.route('/api/todos/clear-completed', methods=['DELETE'])
def clear_completed_todos():
    """一键清除所有已完成的待办事项"""
    # 查询所有已完成的待办
    completed_todos = Todo.query.filter_by(completed=True).all()
    count = len(completed_todos)
    
    # 批量删除
    for todo in completed_todos:
        db.session.delete(todo)
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'count': count,
        'message': f'成功清除 {count} 个已完成的待办事项'
    })

